package cn.zhenglili.uflodemo.config.database;

import cn.zhenglili.uflodemo.provider.EnvironmentProviderImpl;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate5.HibernateTransactionManager;

@Configuration
public class TransactionManagerConfig {
    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    @Bean(name="transactionManager")
    public HibernateTransactionManager createHibernateTransactionManager(){
        HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
        hibernateTransactionManager.setSessionFactory(sessionFactory);
        return hibernateTransactionManager;
    }

    @Bean
    public EnvironmentProviderImpl createEnvironmentProviderImpl(){
        EnvironmentProviderImpl environmentProvider = new EnvironmentProviderImpl();
        // 设置EnvironmentProviderImpl的两个变量：sessionFactory transactionManager
        environmentProvider.setSessionFactory(sessionFactory);
        environmentProvider.setPlatformTransactionManager(this.createHibernateTransactionManager());
        return environmentProvider;
    }
}
